﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramWindow.BLL
{
    class Win32BLL
    {
        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        private static extern int SetCursorPos(int x, int y);

        [DllImport("user32")]
        private extern static void mouse_event(int dwFlag, int dx, int dy, int dwData, IntPtr deExtraInfo);

        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
        public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

        [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsDelegate lpEnumCallbackFunction, IntPtr lParam);

        //[DllImport("user32.dll", EntryPoint = "SendMessage")]
        //public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        // 给窗口发送消息
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        // 给窗口发送消息，事件返回的数据通过Byte[]数组获得
        [DllImport("user32.dll", EntryPoint = "SendMessageA")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, Byte[] lParam);
        public delegate bool EnumDesktopWindowsDelegate(IntPtr hWnd, uint lParam);
        private static readonly object MouseLock = new object();
        public const int KEYEVENTF_KEYDOWN = 0;
        public const int KEYEVENTF_KEYUP = 2;


        public static void MouseClick(System.Windows.Point p)
        {
            lock (MouseLock)
            {
                //Point point = Control.MousePosition;
                SetCursorPos(Convert.ToInt32(p.X), Convert.ToInt32(p.Y));
                mouse_event(2, 0, 0, 0, IntPtr.Zero);
                //Delay(50);
                mouse_event(4, 0, 0, 0, IntPtr.Zero);
                //Delay(50);
                //SetCursorPos(point.X, point.Y);
            }
        }
        public static void KeyDown(Keys key)
        {
            keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
        }
        public static void KeyDown(Keys key1, Keys key2)
        {
            keybd_event(key1, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key2, 0, KEYEVENTF_KEYDOWN, 0);
            //Delay(50);
            keybd_event(key1, 0, KEYEVENTF_KEYUP, 0);
            //Delay(50);
            keybd_event(key2, 0, KEYEVENTF_KEYUP, 0);
        }
    }
}
